package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipInputStream;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private ServiceItemMapper serviceItemMapper;
    @Autowired
    private IServiceItemService serviceItemService;


    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }


    @Override
    public void save(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.insert(carPackageAudit);
    }


    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long id : dictIds) {
            carPackageAuditMapper.deleteByPrimaryKey(id);

        }
    }

    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }

    @Override
    public InputStream getProcessImageByAuditId(Long id) {
        CarPackageAudit carPackageAudit = this.get(id);
        BpmnInfo bpmnInfo = bpmnInfoService.get(carPackageAudit.getBpmnInfoId());
        InputStream inputStream = null;
        //如果状态为审核中，说明还正在流程中
        if (carPackageAudit.getStatus().equals(CarPackageAudit.STATUS_IN_ROGRESS)) {
            //查询当前节点 ,找节点长宽高放入坐标 绘制节点高亮显示框
            Task task = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
            List<String> activeActivityIds = runtimeService.getActiveActivityIds(task.getExecutionId());

            inputStream = this.getProcessImage(
                    bpmnInfo.getActProcessId(),
                    activeActivityIds,
                    Collections.EMPTY_LIST);
        } else {   // 审核拒绝
            inputStream = this.getProcessImage(
                    bpmnInfo.getActProcessId(),
                    Collections.EMPTY_LIST,
                    Collections.EMPTY_LIST);
        }

        return inputStream;
    }
    private InputStream getProcessImage(String processDefinitionId, List<String> highLightedActivities, List<String> highLightedFlows) {
        BpmnModel model = repositoryService.getBpmnModel(processDefinitionId);
        ProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        //generateDiagram(流程模型,需要高亮的节点,需要高亮的线条,后面三个参数都表示是字体)
        InputStream inputStream = generator.generateDiagram(model, highLightedActivities, highLightedFlows, "宋体", "宋体", "宋体");
        return inputStream;
    }


    @Override//审核撤销
    public void cancelApply(Long id) {

        //记录id
        CarPackageAudit audit = this.get(id);

        carPackageAuditMapper.changeAuditStatus(id,CarPackageAudit.STATUS_CANCEL);
        serviceItemMapper.changeAuditStatus(ServiceItem.AUDITSTATUS_INIT,audit.getServiceItemId());

        runtimeService.deleteProcessInstance(audit.getInstanceId(),"审核撤销");

    }

    @Override
    public void audit(Long id, int auditStatus, String info) {
        CarPackageAudit audit = this.get(id);
        //只有在审核中的状态才可以审核

//审核 通过 时
        // 1-如果还有下一个节点:
        //流程审核记录表 修改当前审核人---财务
        //流程审核记录表记录当前审核时间

        // 2-如果没有下一个节点:
        //套餐服务单项状态 改为 通过
        //流程审核记录状态 改为 通过

//审核 拒绝 时
        //套餐单项服务状态改为初始化  建议加一个状态审核拒绝  改动逻辑    到时候套餐发起审核的时候 初始化和审核拒绝都可以点击发起审核按钮
        //流程审核记录状态: 审核拒绝


        String userName = ShiroUtils.getUser().getUserName();
        String commentStr = auditStatus == CarPackageAudit.STATUS_PASS ? "【" + userName + "同意】" : "【" + userName + "拒绝】";

        if (StringUtils.isNotEmpty(info)) {
            info += commentStr;
            audit.setInfo(audit.getInfo() + "<br>" + info);
        }
        audit.setAuditTime(new Date());

        //获取当前任务task 以拿到taskId
        Task task = taskService.createTaskQuery().processInstanceId(audit.getInstanceId()).singleResult();
        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(audit.getInstanceId()).singleResult();

        //添加备注
        taskService.addComment(task.getId(), task.getProcessInstanceId(), info);
        //设置审核操作的同意与否 的页面参数
        taskService.setVariable(task.getId(), "auditStatus", auditStatus);
        //完成任务
        taskService.complete(task.getId());

        //下一个任务节点 (流程自动推进)
        Task nextTask = taskService.createTaskQuery().processInstanceId(audit.getInstanceId()).singleResult();

        if (auditStatus == CarPackageAudit.STATUS_PASS) {   // 1拒绝  2同意


            //如果通过
            if (nextTask == null) {
                //下一个任务为空，审核结束
                audit.setStatus(CarPackageAudit.STATUS_PASS);
                serviceItemService.changeAuditStatus(audit.getServiceItemId(), ServiceItem.AUDITSTATUS_APPROVED);
            } else {
                //下一个任务不为空，审核继续
                audit.setAuditorId(Long.parseLong(nextTask.getAssignee()));
            }




        } else {


            //如果拒绝-审核结束
            audit.setStatus(CarPackageAudit.STATUS_REJECT);
            serviceItemService.changeAuditStatus(audit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);


        }

        carPackageAuditMapper.updateByPrimaryKey(audit); //  修改记录表的信息



    }


}